<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模板方法模式与钩子方法的配合使用</title>
    <link href="https://cdn.staticfile.org/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.staticfile.org/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/mermaid@latest/dist/mermaid.min.js"></script>
    <style>
        body {
            font-family: 'Noto Sans SC', Tahoma, Arial, Roboto, "Droid Sans", "Helvetica Neue", "Droid Sans Fallback", "Heiti SC", "Hiragino Sans GB", Simsun, sans-serif;
            color: #333;
            line-height: 1.6;
        }
        h1, h2, h3, h4 {
            font-family: 'Noto Serif SC', serif;
            font-weight: 600;
        }
        .hero {
            background: linear-gradient(135deg, #6e8efb 0%, #4a6cf7 100%);
            color: white;
        }
        .code-block {
            background: #282c34;
            border-radius: 8px;
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .card {
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0,0,0,0.1);
        }
        .highlight {
            position: relative;
        }
        .highlight:before {
            content: "";
            position: absolute;
            left: -8px;
            top: 0;
            height: 100%;
            width: 4px;
            background: #4a6cf7;
            border-radius: 2px;
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Hero Section -->
    <section class="hero py-20 px-4">
        <div class="container mx-auto max-w-5xl text-center">
            <h1 class="text-4xl md:text-5xl font-bold mb-6">模板方法模式与钩子方法的配合使用</h1>
            <p class="text-xl md:text-2xl opacity-90 mb-8">设计模式中的灵活组合，实现算法的可扩展性</p>
            <div class="flex justify-center space-x-4">
                <span class="px-4 py-2 bg-white bg-opacity-20 rounded-full">行为型设计模式</span>
                <span class="px-4 py-2 bg-white bg-opacity-20 rounded-full">算法框架</span>
                <span class="px-4 py-2 bg-white bg-opacity-20 rounded-full">可扩展性</span>
            </div>
        </div>
    </section>

    <!-- Main Content -->
    <main class="container mx-auto max-w-5xl px-4 py-12">
        <!-- Introduction -->
        <section class="mb-16">
            <div class="highlight bg-white p-8 rounded-lg shadow-md">
                <p class="text-lg leading-relaxed">
                    模板方法模式（Template Method Pattern）是行为型设计模式的一种，通过在基类中定义算法的骨架，允许子类覆盖部分步骤，从而实现算法的不同实现。而钩子方法（Hook Method）是模板方法模式中的一个关键点，用于在算法的执行过程中插入可选的、子类可以重写的扩展点。
                </p>
                <p class="text-lg leading-relaxed mt-4">
                    这种组合设计能带来极大的灵活性与扩展性，尤其适合在框架或工具类库中提供通用的算法模板，同时允许具体实现者定制部分行为。
                </p>
            </div>
        </section>

        <!-- Core Concept -->
        <section class="mb-16">
            <h2 class="text-3xl font-bold mb-8 text-center border-b pb-4">1. 模板方法模式的核心思想</h2>
            <p class="text-lg mb-6">模板方法模式的主要思想是定义算法的固定框架，让算法的部分步骤延迟到子类去实现。</p>
            
            <div class="grid md:grid-cols-3 gap-6 mb-10">
                <div class="card bg-white p-6 rounded-lg">
                    <div class="text-blue-500 mb-4">
                        <i class="fas fa-sitemap text-3xl"></i>
                    </div>
                    <h3 class="text-xl font-semibold mb-3">模板方法</h3>
                    <p class="text-gray-600">在父类中定义一个不可修改的公共方法，规定了算法的步骤和顺序。</p>
                </div>
                <div class="card bg-white p-6 rounded-lg">
                    <div class="text-blue-500 mb-4">
                        <i class="fas fa-puzzle-piece text-3xl"></i>
                    </div>
                    <h3 class="text-xl font-semibold mb-3">抽象方法</h3>
                    <p class="text-gray-600">定义步骤中必须由子类提供实现的部分。</p>
                </div>
                <div class="card bg-white p-6 rounded-lg">
                    <div class="text-blue-500 mb-4">
                        <i class="fas fa-hook text-3xl"></i>
                    </div>
                    <h3 class="text-xl font-semibold mb-3">钩子方法</h3>
                    <p class="text-gray-600">提供默认实现，子类可以选择性地重写，决定是否扩展算法或修改其行为。</p>
                </div>
            </div>
        </section>

        <!-- Hook Method -->
        <section class="mb-16">
            <h2 class="text-3xl font-bold mb-6 border-b pb-4">2. 钩子方法的作用</h2>
            <p class="text-lg mb-6">钩子方法的主要功能是增强模板方法的灵活性，使子类可以：</p>
            
            <div class="grid md:grid-cols-3 gap-6 mb-8">
                <div class="bg-blue-50 p-6 rounded-lg">
                    <div class="flex items-center mb-3">
                        <i class="fas fa-check-circle text-blue-500 mr-2"></i>
                        <h3 class="font-medium">决定步骤执行</h3>
                    </div>
                    <p>通过返回布尔值来控制模板方法中的某些逻辑是否启用。</p>
                </div>
                <div class="bg-blue-50 p-6 rounded-lg">
                    <div class="flex items-center mb-3">
                        <i class="fas fa-sliders-h text-blue-500 mr-2"></i>
                        <h3 class="font-medium">调整默认行为</h3>
                    </div>
                    <p>通过覆写钩子方法改变默认实现。</p>
                </div>
                <div class="bg-blue-50 p-6 rounded-lg">
                    <div class="flex items-center mb-3">
                        <i class="fas fa-plus-circle text-blue-500 mr-2"></i>
                        <h3 class="font-medium">插入额外逻辑</h3>
                    </div>
                    <p>在算法的固定步骤中增加定制的操作。</p>
                </div>
            </div>
        </section>

        <!-- Example -->
        <section class="mb-16">
            <h2 class="text-3xl font-bold mb-6 border-b pb-4">3. 模板方法模式与钩子方法配合的典型实现</h2>
            <p class="text-lg mb-6">以下是一个具体的示例，展示模板方法模式和钩子方法的协作。</p>
            
            <h3 class="text-2xl font-semibold mb-4">示例：饮料制作过程</h3>
            <p class="mb-6">抽象类 <code class="bg-gray-100 px-2 py-1 rounded">Beverage</code> 定义了制作饮料的模板方法和钩子方法。</p>
            
            <div class="code-block p-4 mb-8 overflow-x-auto">
                <pre class="text-gray-200"><code>abstract class Beverage {
    // 模板方法，定义制作饮料的固定步骤
    public final void prepareRecipe() {
        boilWater();
        brew();
        pourInCup();
        if (customerWantsCondiments()) { // 钩子方法
            addCondiments();
        }
    }

    // 公共步骤
    private void boilWater() {
        System.out.println("Boiling water");
    }

    private void pourInCup() {
        System.out.println("Pouring into cup");
    }

    // 抽象方法，由子类实现
    protected abstract void brew();

    protected abstract void addCondiments();

    // 钩子方法，子类可以选择重写
    protected boolean customerWantsCondiments() {
        return true; // 默认需要调料
    }
}</code></pre>
            </div>
            
            <h3 class="text-2xl font-semibold mb-4 mt-8">具体实现：制作茶和咖啡</h3>
            <div class="code-block p-4 mb-6 overflow-x-auto">
                <pre class="text-gray-200"><code>class Tea extends Beverage {
    @Override
    protected void brew() {
        System.out.println("Steeping the tea");
    }

    @Override
    protected void addCondiments() {
        System.out.println("Adding lemon");
    }

    // 茶不需要额外调料
    @Override
    protected boolean customerWantsCondiments() {
        return false;
    }
}

class Coffee extends Beverage {
    @Override
    protected void brew() {
        System.out.println("Dripping coffee through filter");
    }

    @Override
    protected void addCondiments() {
        System.out.println("Adding sugar and milk");
    }
}</code></pre>
            </div>
            
            <h3 class="text-2xl font-semibold mb-4 mt-8">运行结果</h3>
            <div class="code-block p-4 mb-6 overflow-x-auto">
                <pre class="text-gray-200"><code>public class TemplateMethodExample {
    public static void main(String[] args) {
        Beverage tea = new Tea();
        System.out.println("Making tea:");
        tea.prepareRecipe();

        Beverage coffee = new Coffee();
        System.out.println("\nMaking coffee:");
        coffee.prepareRecipe();
    }
}</code></pre>
            </div>
            
            <div class="bg-gray-100 p-6 rounded-lg mt-6">
                <h4 class="font-semibold mb-2">输出：</h4>
                <pre class="bg-white p-4 rounded"><code>Making tea:
Boiling water
Steeping the tea
Pouring into cup

Making coffee:
Boiling water
Dripping coffee through filter
Pouring into cup
Adding sugar and milk</code></pre>
            </div>
        </section>

        <!-- Advantages -->
        <section class="mb-16">
            <h2 class="text-3xl font-bold mb-8 border-b pb-4">4. 模板方法模式与钩子方法的优点</h2>
            <div class="grid md:grid-cols-2 gap-8">
                <div class="bg-white p-6 rounded-lg shadow-sm">
                    <div class="flex items-center mb-4">
                        <div class="bg-blue-100 p-2 rounded-full mr-3">
                            <i class="fas fa-lock text-blue-500"></i>
                        </div>
                        <h3 class="text-xl font-semibold">固定算法框架</h3>
                    </div>
                    <p>模板方法确保了算法的整体结构不变，提供了统一的实现规范。</p>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm">
                    <div class="flex items-center mb-4">
                        <div class="bg-blue-100 p-2 rounded-full mr-3">
                            <i class="fas fa-expand-arrows-alt text-blue-500"></i>
                        </div>
                        <h3 class="text-xl font-semibold">灵活扩展点</h3>
                    </div>
                    <p>钩子方法为子类提供了灵活性，子类可以按需扩展或调整具体逻辑。</p>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm">
                    <div class="flex items-center mb-4">
                        <div class="bg-blue-100 p-2 rounded-full mr-3">
                            <i class="fas fa-shield-alt text-blue-500"></i>
                        </div>
                        <h3 class="text-xl font-semibold">遵循开闭原则</h3>
                    </div>
                    <p>新增行为只需修改子类，不影响模板方法的实现。</p>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm">
                    <div class="flex items-center mb-4">
                        <div class="bg-blue-100 p-2 rounded-full mr-3">
                            <i class="fas fa-code text-blue-500"></i>
                        </div>
                        <h3 class="text-xl font-semibold">减少代码重复</h3>
                    </div>
                    <p>通用部分放在父类中实现，子类仅需关注个性化逻辑。</p>
                </div>
            </div>
        </section>

        <!-- Application -->
        <section class="mb-16">
            <h2 class="text-3xl font-bold mb-6 border-b pb-4">5. 应用场景</h2>
            <p class="text-lg mb-8">模板方法模式与钩子方法的结合广泛应用于以下场景：</p>
            
            <div class="flex flex-col space-y-6">
                <div class="flex items-start">
                    <div class="bg-blue-500 text-white rounded-full w-8 h-8 flex items-center justify-center flex-shrink-0 mr-4">
                        <i class="fas fa-cube"></i>
                    </div>
                    <div>
                        <h3 class="text-xl font-semibold mb-2">框架与工具类开发</h3>
                        <p>如 Spring 的 <code class="bg-gray-100 px-1 py-0.5 rounded">BeanPostProcessor</code> 定义了模板方法，提供多个钩子方法供开发者扩展。</p>
                    </div>
                </div>
                <div class="flex items-start">
                    <div class="bg-blue-500 text-white rounded-full w-8 h-8 flex items-center justify-center flex-shrink-0 mr-4">
                        <i class="fas fa-project-diagram"></i>
                    </div>
                    <div>
                        <h3 class="text-xl font-semibold mb-2">工作流或任务处理</h3>
                        <p>如定制化的工作流系统中，开发者通过钩子方法调整具体任务的执行逻辑。</p>
                    </div>
                </div>
                <div class="flex items-start">
                    <div class="bg-blue-500 text-white rounded-full w-8 h-8 flex items-center justify-center flex-shrink-0 mr-4">
                        <i class="fas fa-brain"></i>
                    </div>
                    <div>
                        <h3 class="text-xl font-semibold mb-2">算法扩展</h3>
                        <p>如机器学习中的数据预处理框架，提供数据加载、清洗等固定流程，并通过钩子方法支持自定义扩展。</p>
                    </div>
                </div>
            </div>
        </section>

        <!-- Optimization -->
        <section class="mb-16">
            <h2 class="text-3xl font-bold mb-6 border-b pb-4">6. 可能的优化与注意事项</h2>
            
            <div class="bg-yellow-50 border-l-4 border-yellow-400 p-6 mb-6">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-500"></i>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-lg font-medium text-yellow-800 mb-2">钩子方法的滥用</h3>
                        <p>过多的钩子方法可能导致子类实现混乱，增加维护成本。应合理控制钩子方法的数量。</p>
                    </div>
                </div>
            </div>
            
            <div class="bg-yellow-50 border-l-4 border-yellow-400 p-6 mb-6">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-500"></i>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-lg font-medium text-yellow-800 mb-2">模板方法的复杂度</h3>
                        <p>模板方法的设计要清晰，避免过长的流程导致难以理解。</p>
                    </div>
                </div>
            </div>
            
            <div class="bg-yellow-50 border-l-4 border-yellow-400 p-6">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-500"></i>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-lg font-medium text-yellow-800 mb-2">钩子方法的默认实现</h3>
                        <p>为钩子方法提供合理的默认行为，避免子类必须实现所有钩子方法。</p>
                    </div>
                </div>
            </div>
        </section>

        <!-- Visualization -->
        <section class="mb-16">
            <h2 class="text-3xl font-bold mb-8 border-b pb-4">模板方法模式结构图</h2>
            <div class="mermaid">
                classDiagram
                    class AbstractClass {
                        <<abstract>>
                        +templateMethod()
                        #primitiveOperation1()*
                        #primitiveOperation2()*
                        #hook() boolean
                    }
                    
                    class ConcreteClassA {
                        #primitiveOperation1()
                        #primitiveOperation2()
                        #hook() boolean
                    }
                    
                    class ConcreteClassB {
                        #primitiveOperation1()
                        #primitiveOperation2()
                        #hook() boolean
                    }
                    
                    AbstractClass <|-- ConcreteClassA
                    AbstractClass <|-- ConcreteClassB
            </div>
        </section>
    </main>

    <!-- Footer -->
    <footer class="bg-gray-900 text-white py-8">
        <div class="container mx-auto max-w-5xl px-4">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <h3 class="text-xl font-semibold">技术小馆</h3>
                </div>
                <div>
                    <a href="http://www.yuque.com/jtostring" class="text-blue-300 hover:text-white transition-colors">
                        http://www.yuque.com/jtostring
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <script>
        mermaid.initialize({
            startOnLoad: true,
            theme: 'default',
            flowchart: {
                useMaxWidth: true,
                htmlLabels: true
            }
        });
    </script>
</body>
</html>